package com.nkym.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.nkym.client.LApiClient;
import com.nkym.common.ErrorCode;
import com.nkym.constants.UserConstant;
import com.nkym.exception.BusinessException;
import com.nkym.mapper.UserInterfaceMapper;
import com.nkym.pojo.dto.IdRequest;
import com.nkym.pojo.dto.interfaceInfo.InterfaceInfoAddRequest;

import com.nkym.pojo.dto.interfaceInfo.InterfaceInfoInvokeRequest;
import com.nkym.pojo.dto.interfaceInfo.InterfaceInfoQueryRequest;
import com.nkym.pojo.dto.interfaceInfo.InterfaceInfoUpdateRequest;
import com.nkym.pojo.entity.InterfaceInfo;
import com.nkym.mapper.InterfaceInfoMapper;
import com.nkym.pojo.entity.User;
import com.nkym.pojo.vo.PageVo;
import com.nkym.service.InterfaceInfoService;
import org.apache.tomcat.util.http.fileupload.servlet.ServletRequestContext;
import org.junit.platform.commons.util.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Arrays;

/**
 * @author 19637
 * @description 针对表【interface_info】的数据库操作Service实现
 * @createDate 2023-04-18 20:51:59
 */
@Service
public class InterfaceInfoServiceImpl extends ServiceImpl<InterfaceInfoMapper, InterfaceInfo>
        implements InterfaceInfoService {
    @Resource
    InterfaceInfoMapper interfaceInfoMapper;
    @Resource
    UserInterfaceMapper userInterfaceMapper;
    @Value("${gateway.host}")
    String host;

    /**
     * 下线接口
     *
     * @param idRequest
     */
    @Override
    public void offline(IdRequest idRequest) {
        Integer id = idRequest.getId();
        if (id == null || id <= 0) {
            throw new BusinessException(ErrorCode.PARAM_EMPTY);
        }
        InterfaceInfo info = interfaceInfoMapper.selectById(id);
        if (info == null) {
            throw new BusinessException(ErrorCode.INTERFACE_EMPTY);
        }
        try {
            interfaceInfoMapper.offline(id);
        } catch (Exception e) {
            throw new BusinessException(ErrorCode.ERROR_CODE);
        }
    }


    /**
     * 上线接口
     *
     * @param idRequest
     */
    @Override
    public void online(IdRequest idRequest) {
        if (idRequest.getId() == null || idRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAM_EMPTY);
        }
        //查询接口存在
        Integer id = idRequest.getId();
        InterfaceInfo info = interfaceInfoMapper.selectById(id);
        if (info == null) {
            throw new BusinessException(ErrorCode.INTERFACE_EMPTY);
        }
        //todo  真实调用接口 查看是否可用
//        String user = apiClient.getUser();
        //如果可用更改接口状态
        try {
            interfaceInfoMapper.online(id);
        } catch (Exception e) {
            throw new BusinessException(ErrorCode.ERROR_CODE);
        }
    }

    @Override
    public PageVo<InterfaceInfo> paginationQuery(InterfaceInfoQueryRequest queryRequest) {
        //todo  参数校验
        QueryWrapper<InterfaceInfo> wrapper = new QueryWrapper<>();
        if (queryRequest.getName() != null) {
            wrapper.likeRight("name", queryRequest.getName());
        }
        IPage<InterfaceInfo> page = new Page<>(queryRequest.getPageNow(), queryRequest.getPageSize());
        IPage<InterfaceInfo> selectPage = interfaceInfoMapper.selectPage(page, wrapper);
        PageVo<InterfaceInfo> pageVo = new PageVo<>();
        pageVo.setData(selectPage.getRecords());
        pageVo.setSize(selectPage.getSize());
        pageVo.setTotal(selectPage.getTotal());
        pageVo.setCurrent(selectPage.getCurrent());
        return pageVo;
    }

    @Override
    @Transactional
    public void addInterfaceInfo(InterfaceInfoAddRequest infoAddRequest, HttpServletRequest request) {

        String name = infoAddRequest.getName();
        String description = infoAddRequest.getDescription();
        String url = infoAddRequest.getUrl();
        String method = infoAddRequest.getMethod();
        String path = infoAddRequest.getPath();
        String requestHeader = infoAddRequest.getRequestHeader();
        String responseHeader = infoAddRequest.getResponseHeader();
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute(UserConstant.USER_LOGIN_STATUS);
        if (user == null) {
            throw new BusinessException(ErrorCode.USER_UNLOGIN);
        }
        if (StringUtils.isBlank(name)) {
            throw new BusinessException(ErrorCode.PARAM_ERROR);
        }
        if (StringUtils.isBlank(description)) {
            throw new BusinessException(ErrorCode.PARAM_ERROR);
        }
        if (StringUtils.isBlank(url)) {
            throw new BusinessException(ErrorCode.PARAM_ERROR);
        }
        if (StringUtils.isBlank(method)) {
            throw new BusinessException(ErrorCode.PARAM_ERROR);
        }
        if (StringUtils.isBlank(path)) {
            throw new BusinessException(ErrorCode.PARAM_ERROR);
        }
        if (StringUtils.isBlank(requestHeader)) {
            throw new BusinessException(ErrorCode.PARAM_ERROR);
        }
        if (StringUtils.isBlank(responseHeader)) {
            throw new BusinessException(ErrorCode.PARAM_ERROR);
        }
        infoAddRequest.setUserId(user.getId());
        InterfaceInfo info = new InterfaceInfo();
        infoAddRequest.setMethod(method.toUpperCase());
        BeanUtil.copyProperties(infoAddRequest, info);
        interfaceInfoMapper.insert(info);
    }


    @Override
    public String invoke(InterfaceInfoInvokeRequest invokeRequest, HttpServletRequest request) {
        Integer id = invokeRequest.getId();
        String requestParam = invokeRequest.getRequestParam();
        if (id == null || StringUtils.isBlank(requestParam)) {
            throw new BusinessException(ErrorCode.PARAM_EMPTY);
        }
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute(UserConstant.USER_LOGIN_STATUS);
        if (user == null) {
            throw new BusinessException(ErrorCode.USER_UNLOGIN);
        }
        InterfaceInfo info = interfaceInfoMapper.selectById(id);
        if (info == null) {
            throw new BusinessException(ErrorCode.INTERFACE_EMPTY);
        }
        String accessKey = user.getAccessKey();
        String secretKey = user.getSecretKey();
        LApiClient apiClient = new LApiClient(accessKey, secretKey);
        String method = info.getMethod();
        String path = info.getPath();

        return doInvoke(apiClient, path, method, requestParam);

    }

    private String doInvoke(LApiClient apiClient, String path, String method, String param) {
        String url = host + path;
        String result = "接口无法调用";
        if ("get".equalsIgnoreCase(method)) {
            result = apiClient.get(url, param);
        } else if ("post".equalsIgnoreCase(method)) {
            result = apiClient.post(url, param);
        } else if ("put".equalsIgnoreCase(method)) {
            result = apiClient.put(url, param);
        }
        return result;
    }

    @Override
    public Integer getInterfaceInfoId(String method, String path) {
        Integer id = interfaceInfoMapper.getInterfaceInfoId(method, path);
        return id;
    }

    @Override
    public void updateInterfaceInfo(InterfaceInfoUpdateRequest infoUpdateRequest) {
        InterfaceInfo interfaceInfo = new InterfaceInfo();
        BeanUtil.copyProperties(infoUpdateRequest, interfaceInfo);
        interfaceInfoMapper.updateById(interfaceInfo);
    }
}




